<template>
  <div class="container">
    <div>
      <div>
        <span 
          @click="$router.back(-1)"
          class="back"
          >{{$t('page.back')}}{{$t('page.list')}}
        </span> > {{$route.query.name}}（{{$route.query.time}}）
      </div>
    </div>
    <div 
      class="container-body"
      v-loading="loading">
      <template>
        <FormParameter v-if="otherParams" :otherParams="otherParams"></FormParameter>

        <div class="title-space">
          <span>{{$t('page.ODvalue')}}：</span>
        </div>

        <div class="overflow">

          <!-- 大表格 -->
          <table 
            id="table-1"
            width="100%"
            v-for="(listItem,listIndex) in smoothList"
            :key="listIndex">
            <tr v-for="(table,key,index) in listItem"
                :key="index">
              <td class="color-000">{{key!=='time'?key:$t('page.hole')}}</td>
              <td>
                <span v-if="key!=='time'">
                  {{beforeLable[index-1]}}
                </span>
                <span class="color-000"
                      v-else>
                  {{$t('page.label')}}
                </span>
              </td>
              <td v-for="(iTable, index) in table"
                  :key="index">
                <span v-if="key!=='time'">{{iTable}}</span>
                <span class="color-000"
                      v-else>{{iTable + 's'}}</span>
              </td>
            </tr>
          </table>
        </div>

        <el-checkbox-group v-if="extB !== 'v1'" v-model="checkList" style="margin:20px 0 40px 20px;">
          <el-checkbox :disabled="checkList.length === 1 && checkList.indexOf('曲线') > -1" :label="$t('page.curve')" />
          <el-checkbox :disabled="checkList.length === 1 && checkList.indexOf('拟合') > -1" :label="$t('page.fitting')" />
        </el-checkbox-group>
        <div class="space text-center">
          <!-- 图形 -->
          <div class="chart"
               v-for="(chart,index) in allStepOneCharts"
               :key="index">
            <wave-chart 
              :id="'logStepOne1'+index"
              :data='chart'
            ></wave-chart>
          </div>
        </div>

        <div class="title-space" v-if="mole">
          <span>{{$t('page.molecular')}}（Da）：</span>
          {{mole}}
        </div>
        <ParamTable :paramResult="paramResult"></ParamTable>
      </template>
    </div>
  </div>
</template>

<script>
import waveChart from '@/components/WaveChart'
import { fetchHistoryDetail } from '@/api/table'
import { COLORLIST } from '@/utils/variate'
import ParamTable from '@/components/ParamTable'
import FormParameter from './form_parameter.vue'
export default {
  data() {
    return {
      loading: true,
      originalData: [],
      allStepOneCharts: [],
      mole: '',
      waveName: [],
      beforeLable: [],
      paramResult: {},
      unit: '',
      smoothList: [], // 大表格数据
      standby: [], // 备用数据
      checkList: ['曲线', '拟合'], 
      extB: 'v2',    
      otherParams: null,
      dissociation: [12, 20]
    }
  },
  components: {
    waveChart,
    ParamTable,
    FormParameter
  },
  mounted() {
    this.getHistoryDetail()
  },
  methods: {
    async getHistoryDetail() {
      const res = await fetchHistoryDetail({
        id: this.$route.query.id,
      })
      this.loading = false
      this.mole = res.data[0]?.mole
      let data = {}
      try {
        // console.log('1234', res.data[0].resultData);
        let str = res.data[0]?.resultData.replace(/\n/g,"\\n").replace(/\r/g,"\\r")
        data = JSON.parse(str) || {}
        this.beforeLable = JSON.parse(res.data[0]?.crpValue)
      } catch(e) {
        return e
      }
      // this.beforeLable = data.computeCrpValue.value
      console.log(data, '亲和力检测（一步法）')
      this.otherParams = data.other_params
      // 新旧表
      this.extB = data.extB
      // 已填写的孔号
      // 备用孔号
      this.waveName2 = data.hole
      this.unit = data.unit
      // this.originalData = this.setSoomth(data.originalData[0], data.originalData_hl_merge[0])
      // 图形数据
      const result = this.$setGrapData(data.originalData_hl_merge[0], data.originalData_hl_merge_fitting[0])
      this.originalData = result.resultList
      this.waveName = result.keyList
      // 大表格数据
      this.smoothList = data.originalData_hl_merge,
      // 备用数据
      this.dissociation = data.dissociation
      this.standby = this.originalData
      this.paramResult = data.result_data_excel
      this.drawChart()
    },

    // 处理图形数据
    // setSoomth(originalData, mergeData) {
    //   let obj1 = {}
    //   for (const k in mergeData) {
    //     if(k !== 'time' ) {
    //       obj1[`拟合${k}`] = mergeData[k]
    //     }
    //   }
    //   this.waveName = [...this.waveName, ...Object.keys(obj1)]
    //   return [{...originalData, ...obj1}]
    // },
    
    drawChart() {
      this.allStepOneCharts = []
      this.originalData.forEach((item, index, arry) => {
        let chartsOption = {
          title: {
            text: '',
          },
          animation: false,
          tooltip: {
            trigger: 'axis',
            enterable: true,
            transitionDuration: 0.8,
            extraCssText: 'height: 300px;overflow-y: auto;width: 400px;',
            // 自定义tootip 
            formatter: (params) => {
              let str = `<p>${ params[0].axisValueLabel }</p>`
              let tipItem = ``
              params.forEach((item, index) => {
                tipItem += `<div 
                  style="
                  width:50%;
                  padding:0 10px;
                  text-align: left;
                  ">
                    <span 
                      style="display:inline-block;
                      margin-right:5px;
                      border-radius:50%;
                      width:10px;
                      height:10px;
                      margin-left:5px;
                      background-color: ${this.test(item.seriesName, index)}">
                    </span>
                    <span>
                    ${item.seriesName}：${item.value}
                </div>`
              })
              let contentBox = `<div style="display: flex;flex-wrap: wrap;width: 100%;">${tipItem}</div>`
              let showContent = `${str}${contentBox}`
              return showContent
            }
          },
          legend: {
            type: 'scroll',
            orient: 'vertical',
            align: 'left',
            right: '0',
            bottom: '20%',
            top: '60',
            data: [],
            icon: 'circle',
            itemGap: 20,
	          itemWidth:20,
            textStyle: {
              fontSize: 20
            },
            padding: [ 0, 0, 10, 0 ],
            // formatter: (name) => {
            //   if(name.indexOf('拟合') > -1) {
            //     // const arr = this.beforeLable.filter(item => +item)
            //     const str = name.slice(2)
            //     const index = this.waveName2.findIndex(item => item === str)
            //     return `拟合${this.beforeLable[index]}`
            //   } else {
            //     const index = this.waveName.findIndex(item => item === name)
            //     return this.beforeLable[index]
            //   }
            // }
          },
          grid: {
            left: '6%',
            right: '10%',
            bottom: '15%',
            containLabel: true,
          },
          dataZoom: [
            {
              type: 'inside',
              height: 15,
              xAxisIndex: 0,
              handleSize: '140%',
              handleStyle: {
                color: '#999',
              },
              filterMode: 'none',
            },
            {
              type: 'inside',
              yAxisIndex: 0,
              width:  15,
              handleSize: '140%',
              handleStyle: {    
                color: '#999',
              },
              filterMode: 'none',
            },
          ],
          toolbox: {
            feature: {
              saveAsImage: {},
            },
          },
          xAxis: {
            type: 'value',
            axisTick: {
              alignWithLabel: true,
            },
            boundaryGap: true,
            name: 'Time/s',
            nameLocation: 'middle',
            nameTextStyle: {
              fontSize: 22,
              padding: 20,
              color: '#000'
            },
            minorTick: {
              show: true
            },
            splitLine: {
              show: false
            },
            axisLabel: {
              fontSize: 20
            },
            data: [],
          },
          yAxis: {
            type: 'value',
            name: 'Relative Response(RU)',
            nameGap: 30,
            splitNumber: 6,
            nameLocation: 'middle',
            nameTextStyle: {
              fontSize: 22,
              padding: 20,
              color: '#000'
            },
            axisLabel: {
              fontSize: 20
            },
          },
          series: [],
        }
        chartsOption.series = []
        chartsOption.xAxis.data = []
        let num = 0
        for (let i in item) {
          if (i !== 'time') {
            const result = this.test(this.waveName[num], num)
            let chartSeries = {
              name: this.waveName[num],
              type: 'line',
              // smooth: true,
              itemStyle: {
                color: result,
                // this.waveName[num].indexOf('拟合')
              },
              lineStyle: {
                width: 2.2
              },
              markLine: {
                symbol: 'none',
                lineStyle: {
                  normal: {
                    color: '#000',
                    
                  },
                },
                data: this.dissociation.map(value => ({xAxis: item['time'][value] || 0})),
                label: {
                  fontSize: 20,
                },
              },
              showSymbol: false,
              hoverAnimation: false,
              data: item[i],
            }
            const titleText = this.extB === 'v1'
            ? this.$t('page.ODvalue') + this.$t('page.curve')
            : `${this.$t('page.curve')}/${this.$t('page.fitting')}`
            chartsOption.title.text = titleText
              
            chartsOption.legend.data = this.waveName
            chartsOption.series.push(chartSeries)
            num++
          } else {
            chartsOption.xAxis.data = item[i]
          }
        }
        this.allStepOneCharts.push(chartsOption)
      })
    },

    // 拟合展示 
    test(name, index) {
      if(name.indexOf('拟合') > -1 && this.checkList.includes('拟合')) {
        if(this.checkList.length > 1) {
          return '#000'
        } else {
          return COLORLIST[index]
        }
      } else {
        return COLORLIST[index]
      }
    }
  },
  watch: {
    // 监听多选变化
    checkList: {
      handler(value) {
        this.waveName = []
        if(value.indexOf('拟合')  > -1 && value.indexOf('曲线') > -1) {
          this.originalData = this.standby
          for (const k in this.standby[0]) {
            if (k !== 'time') {
              this.waveName.push(k)
            }
          }
        } else if(value.indexOf('拟合') > -1) {
          const obj = {}
          for (const k in this.standby[0]) {
            if (k.indexOf('拟合') > -1 || k === 'time' ) {
              obj[k] = this.standby[0][k]
              k !== 'time'? this.waveName.push(k): ''
            }
          }          
          this.originalData = [obj]

        } else {
          const obj = {}
          for (const k in this.standby[0]) {
            if (k.indexOf('拟合') === -1 || k === 'time' ) {
              obj[k] = this.standby[0][k]
              k !== 'time'? this.waveName.push(k): ''
            } 
          }
          this.originalData = [obj]
        }
        this.drawChart()
      },
      deep: true
    }
  },
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
    background-color:#409eff;
    border-color: #409eff;
  }
  .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
    border-color: #fff;
  }
  .el-checkbox__input.is-disabled+span.el-checkbox__label {
    color: #409eff;
  }
}

.container {
  padding: 20px;
}
.back {
  color: #028cdf;
  cursor: pointer;
}
table {
  border-collapse: collapse;
  text-align: center;
  white-space: nowrap;
  margin-bottom: 20px;
}
.img-list {
  width: 1000px;
  display: flex;
  flex-wrap: wrap;
}
.img-item {
  width: 500px;
}

#table-2 {
  border-bottom-width: 1px;
  border-bottom-style: solid;
  border-bottom-color: #000;
}
#table-2 tr {
  border: 1px solid #000 !important;
}

#table-2 td:first-child {
  border-left: 1px solid #000;
}

/* Padding and font style */
#table-2 td,
#table-2 th {
  padding: 10px 15px;
  font-size: 12px;
  font-family: Verdana;
  border-right-width: 1px;
  border-right-style: solid;
}

.data-item {
  display: block;
}

@media screen and (min-width: 1000px) {
  .data-item {
    display: inline-block;
    margin-right: 20px;
  }
}
</style>